package tech

import "ssp/set"

func (s *Solve) ChuteRemotePairs(g *Grid) (used bool, results []*Result) {
	for i := range 3 {
		if ok, rs := g.chuteRemotePairsHouse(g.rows[i*3 : i*3+3]); ok {
			results = append(results, rs...)
			used = true
		}
	}

	for i := range 3 {
		if ok, rs := g.chuteRemotePairsHouse(g.cols[i*3 : i*3+3]); ok {
			results = append(results, rs...)
			used = true
		}
	}
	return
}

func (g *Grid) chuteRemotePairsHouse(lines []House) (used bool, results []*Result) {
	for i, line1 := range lines[:2] {
		for _, cell1 := range line1.cells {
			if cell1.solved() || cell1.cands.Count() != 2 {
				continue
			}
			for j, line2 := range lines[i+1:] {
				for _, cell2 := range line2.cells {
					if cell2.solved() || cell2.boxNum == cell1.boxNum || cell2.cands != cell1.cands {
						continue
					}
					n1 := i
					n2 := i + j + 1
					n3 := 3 - n1 - n2
					cands := set.NewSet()
					midCells := []*Cell{}
					for _, cell := range lines[n3].cells {
						if cell.boxNum == cell1.boxNum || cell.boxNum == cell2.boxNum {
							continue
						}
						midCells = append(midCells, cell)
						if cell.solved() {
							cands.Add(toCand(cell.value))
						} else {
							cands = cands.Union(cell.cands)
						}
					}
					rmCands := cell1.cands.Intersect(cands)
					if rmCands.Count() == 2 {
						break
					}
					if rmCands.Count() == 0 {
						rmCands = cell1.cands
					}

					//fmt.Println("@@@@", cell1, cell2, cands, rmCands)
					rmCells := []*Cell{}
					for _, cell := range line1.cells {
						if cell.solved() || cell.boxNum != cell2.boxNum {
							continue
						}
						if cell.canRemoveCands(rmCands) {
							rmCells = append(rmCells, cell)
						}
					}
					for _, cell := range line2.cells {
						if cell.solved() || cell.boxNum != cell1.boxNum {
							continue
						}
						if cell.canRemoveCands(rmCands) {
							rmCells = append(rmCells, cell)
						}
					}
					//fmt.Println("@@@@", cell1, cell2, rmCells)
					if len(rmCells) == 0 {
						break
					}
					used = true
					result := new(Result)
					result.addRemoved(rmCands, rmCells)
					g1 := result.getHelpCandsGroup()
					g1.add(cell1.cands, []*Cell{cell1, cell2})
					result.addHelpCells([]*Cell{cell1, cell2})
					result.addHelpCells(midCells)
					result.setStrategyName("Chute Remote Pairs")
					results = append(results, result)
				}

			}
		}

	}
	return
}
